package com.grouponmall.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.grouponmall.model.Deal;

/**
 * @author xueqiang.mi
 * @since 2010-6-1
 * @modified 2010-10-10
 */
public class GrouponDealParser {

  public static Deal extractInfo(Document doc) {
    // Extract deal information from the document
    String nowTime = doc.getFirstChild().getAttributes().getNamedItem("date").getNodeValue();
    NodeList deals = doc.getElementsByTagName("deal");
    if (deals.getLength() == 0) {
      return null;
    }
    Deal deal = new Deal();
    Node dealNode = deals.item(0);
    NodeList dealInfoList = dealNode.getChildNodes();
    for (int i = 0; i < dealInfoList.getLength(); i++) {
      Node infoNode = dealInfoList.item(i);
      if (infoNode.getNodeName().equals("division_name")) {
        deal.setCity(infoNode.getFirstChild().getNodeValue().trim());
      } else if (infoNode.getNodeName().equals("title")) {
        deal.setTitle(infoNode.getFirstChild().getNodeValue());
      } else if (infoNode.getNodeName().equals("value")) {
        String tmp = changeFormat(infoNode);
        deal.setRetailValue("$" + tmp);
      } else if (infoNode.getNodeName().equals("discount_amount")) {
        String tmp = changeFormat(infoNode);
        deal.setDiscount("$" + tmp);
      } else if (infoNode.getNodeName().equals("price")) {
        String tmp = changeFormat(infoNode);
        deal.setPrice("$" + tmp);
      } else if (infoNode.getNodeName().equals("end_date")) {
        String endTime = infoNode.getFirstChild().getNodeValue();
        deal.setTimeStart(nowTime);
        deal.setTimeEnd(endTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
        long time_left = 0;
        try {
          time_left = sdf.parse(endTime).getTime() - sdf.parse(nowTime).getTime();
        } catch (ParseException e) {
          // e.printStackTrace();
          time_left = 0;
        }
        long day = 0;
        long hours = 0;
        long minutes = 0;
        day = time_left / (1000 * 60 * 60 * 24);
        hours = (time_left % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        minutes = ((time_left % (1000 * 60 * 60 * 24)) % (1000 * 60 * 60)) / (1000 * 60);
        deal.setTimeLeft(new StringBuilder().append(day).append(" days ").append(hours).append(" hours ").append(
          minutes).append(" minutes").toString());
      } else if (infoNode.getNodeName().equals("large_image_url")) {
        deal.setImage(infoNode.getFirstChild().getNodeValue());
      }
    }
    return deal;
  }

  private static String changeFormat(Node infoNode) {
    String tmp = infoNode.getFirstChild().getNodeValue();
    if (tmp.contains(".00USD") || tmp.contains(".00CAD")) {
      tmp = tmp.substring(0, tmp.indexOf(".00"));
    }
    return tmp;
  }
}
